import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Company, CompanyParam } from './model';

/**
 * 分页查询公司
 */
export async function pageCompany(params: CompanyParam) {
  const res = await request.get<ApiResult<PageResult<Company>>>(
    '/employ/company/page',
    { params }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询公司列表
 */
export async function listCompany(params?: CompanyParam) {
  const res = await request.get<ApiResult<Company[]>>('/employ/company', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询公司
 */
export async function getCompany(id: number) {
  const res = await request.get<ApiResult<Company>>('/employ/company' + id);
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加公司
 */
export async function addCompany(data: Company) {
  const res = await request.post<ApiResult<unknown>>('/employ/company', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改公司
 */
export async function updateCompany(data: Company) {
  const res = await request.put<ApiResult<unknown>>('/employ/company', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除公司
 */
export async function removeCompany(id?: number) {
  const res = await request.delete<ApiResult<unknown>>('/employ/company/' + id);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除公司
 */
export async function removeCompanyBatch(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    '/employ/company/batch',
    {
      data
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改公司状态
 */
export async function updateCompanyStatus(companyId?: number, status?: number) {
  const res = await request.put<ApiResult<unknown>>('/employ/company/status', {
    companyId,
    status
  });
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 检查公司是否存在
 */
export async function checkExistence(
  field: string,
  value: string,
  id?: number
) {
  const res = await request.get<ApiResult<unknown>>(
    '/employ/company/existence',
    {
      params: { field, value, id }
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
